package com.ansion.commonchat.startup.workmanager.bwork.utils;

import androidx.annotation.NonNull;

import java.util.ArrayDeque;
import java.util.concurrent.Executor;

/**
 * Created by wanghongjie on 2023/5/11
 * Describe : 实现了 Executor 接口，用于串行执行任务。
 * <p>
 * 它通过维护一个任务队列和当前任务的运行状态，确保任务按照它们被提交的顺序进行执行
 */
public class BSerialExecutor implements Executor {
    private final ArrayDeque<Task> mTasks;
    private final Executor mExecutor;
    private final Object mLock;
    private volatile Runnable mActive;

    public BSerialExecutor(@NonNull Executor executor) {
        mExecutor = executor;
        mTasks = new ArrayDeque<>();
        mLock = new Object();
    }

    @Override
    public void execute(@NonNull Runnable command) {
        synchronized (mLock) {
            mTasks.add(new Task(this, command));
            if (mActive == null) {
                scheduleNext();
            }
        }
    }

    void scheduleNext() {
        synchronized (mLock) {
            if ((mActive = mTasks.poll()) != null) {
                mExecutor.execute(mActive);
            }
        }
    }

    static class Task implements Runnable {
        final BSerialExecutor mSerialExecutor;
        final Runnable mRunnable;

        Task(@NonNull BSerialExecutor serialExecutor, @NonNull Runnable runnable) {
            mSerialExecutor = serialExecutor;
            mRunnable = runnable;
        }

        @Override
        public void run() {
            try {
                mRunnable.run();
            } finally {
                mSerialExecutor.scheduleNext();
            }
        }
    }
}
